'=====================================================================
'
'  File:    Instructions.cs for Manufacturing Instructions XML Example
'  Summary: Winform for displaying manufacturing instructions stored in
'			the AdventureWorks OLTP database.
'  Date:	January 20, 2006
'
'---------------------------------------------------------------------
'  This file is part of the Microsoft SQL Server Code Samples.
'  Copyright (C) Microsoft Corporation.  All rights reserved.
'
'  This source code is intended only as a supplement to Microsoft
'  Development Tools and/or on-line documentation.  See these other
'  materials for detailed information regarding Microsoft code samples.
'
'  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
'  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
'  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
'  PARTICULAR PURPOSE.
'======================================================= 

Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Data
Imports System.Net
Imports System.Net.Cache
Imports System.IO
Imports System.Globalization
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl
Imports System.Web
Imports System.Data.SqlClient
Imports System.Data.SqlTypes

''' <summary>
''' Summary description for form.
''' </summary>

Partial Public Class Instructions 'The Partial modifier is only required on one class definition per project.
    Inherits System.Windows.Forms.Form
    Private Const prettyXmlXsltFileName As String = "..\..\defaultss.xslt"
    Private Const instructionsXsltFileName As String = "..\..\ManuInstructions.xsl"

    ''' <summary>
    ''' Required designer variable.
    ''' </summary>
    Private components As System.ComponentModel.IContainer = Nothing

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Shared Function GetSoapRequestXml(ByVal productModelID As Integer) As String
        Return "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" _
            & "  <soap:Body>" _
            & "<GetManuInstructions xmlns='testns'>" _
            & "   <ProductModelID>" _
            & productModelID.ToString(System.Globalization.CultureInfo.InvariantCulture) _
            & "</ProductModelID>" _
            & "</GetManuInstructions>" _
            & "  </soap:Body>" _
            & "</soap:Envelope>"
    End Function

    Private Shared Function PostSoapRequest(ByVal requestXml As String) As Stream
        Dim soapWebRequest As HttpWebRequest = CType(WebRequest.Create("http://localhost/manuinstructions/"), HttpWebRequest)
        soapWebRequest.Accept = "text/xml"
        soapWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "identity, gzip;q=0")
        soapWebRequest.ContentType = "text/xml"
        soapWebRequest.CachePolicy = New RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
        soapWebRequest.Headers.Add("SOAPAction", "")
        soapWebRequest.Credentials = CredentialCache.DefaultCredentials
        soapWebRequest.Method = "POST"

        Dim webStream As Stream = soapWebRequest.GetRequestStream()
        Using webWriter As New StreamWriter(webStream)
            Try
                webWriter.Write(requestXml)
                webWriter.Flush()
            Finally
                'webWriter.Close();
            End Try
        End Using

        Dim response As WebResponse = soapWebRequest.GetResponse()
        Return response.GetResponseStream()
    End Function

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowInstructionsButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowInstructionsButton.Click
        Try
            Dim productModelID As Integer = Integer.Parse(ProductModelIDTextBox.Text, CultureInfo.InvariantCulture)
            Dim requestXML As String = GetSoapRequestXml(productModelID)
            Dim webResponseStream As Stream = PostSoapRequest(requestXML)
            Try
                Dim xslt As New XslCompiledTransform(True)
                Using xsltStreamReader As StreamReader = File.OpenText(instructionsXsltFileName)
                    Using xsltXmlReader As XmlReader = XmlReader.Create(xsltStreamReader)
                        xslt.Load(xsltXmlReader)
                    End Using
                End Using

                Dim xmlResults As New XPathDocument(webResponseStream)
                Dim navigator As XPathNavigator = xmlResults.CreateNavigator()
                Dim namespaces As New XmlNamespaceManager(navigator.NameTable)
                namespaces.AddNamespace("z", "http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions")

                Dim expr As XPathExpression = navigator.Compile("//z:root")
                expr.SetContext(namespaces)
                Dim iterator As XPathNodeIterator = navigator.Select(expr)
                If iterator.Count = 0 Then
                    webBrowser1.DocumentText = String.Format(System.Globalization.CultureInfo.InvariantCulture, "<BODY>Product {0} not found.<BODY>", productModelID)
                Else
                    Dim resultStringWriter As New StringWriter(CultureInfo.InvariantCulture)
                    Dim resultXmlWriter As New XmlTextWriter(resultStringWriter)

                    If iterator.MoveNext() Then
                        Dim destinationPath As String = "about:blank"
                        Dim diagNavigator As XPathNavigator = iterator.Current.SelectSingleNode("//z:step/z:diag", namespaces)
                        If Not (diagNavigator Is Nothing) Then
                            Dim diagID As String = diagNavigator.Value

                            destinationPath = Path.ChangeExtension(Path.GetTempFileName(), ".svg")
                            Using destinationFile As TextWriter = File.CreateText(destinationPath)
                                Using conn As New SqlConnection(My.Settings.Default.ConnectionString)
                                    Dim cmd As SqlCommand = conn.CreateCommand()
                                    cmd.CommandText = "SELECT Diagram FROM Production.Illustration WHERE IllustrationID = @IllustrationID"
                                    cmd.Parameters.Add("@IllustrationID", SqlDbType.Int)
                                    cmd.Parameters(0).Value = Integer.Parse(diagID, System.Globalization.CultureInfo.InvariantCulture)

                                    conn.Open()
                                    Dim r As SqlDataReader = cmd.ExecuteReader()
                                    If Not (r Is Nothing) AndAlso r.Read() Then
                                        Dim reader As System.Xml.XmlReader = XmlReader.Create(New StringReader(CStr(r.GetValue(0))))

                                        Dim doc As New XmlDocument()
                                        doc.Load(reader)
                                        Dim root As XmlElement = doc.DocumentElement
                                        root.SetAttribute("viewbox", "0, 0, " & root.GetAttribute("width") & "," & root.GetAttribute("height"))
                                        root.SetAttribute("width", "200")
                                        root.SetAttribute("height", "150")
                                        doc.Save(destinationFile)
                                    End If
                                End Using

                            End Using
                        End If

                        Dim args As New XsltArgumentList()
                        args.AddParam("svgUrl", "", destinationPath)
                        xslt.Transform(iterator.Current.Clone(), args, resultXmlWriter)
                    End If

                    resultXmlWriter.Flush()

                    Dim result As String = resultStringWriter.ToString()
                    webBrowser1.DocumentText = result
                End If
            Finally
                webResponseStream.Dispose()
            End Try
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowResponseButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowResponseButton.Click
        Try
            Dim productModelID As Integer = Integer.Parse(ProductModelIDTextBox.Text, CultureInfo.InvariantCulture)
            Dim requestXML As String = GetSoapRequestXml(productModelID)
            Using webResponseStream As Stream = PostSoapRequest(requestXML)
                Dim xmlResults As New XPathDocument(webResponseStream)
                TransformAndBrowseDocument(xmlResults)
            End Using
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowRequestButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowRequestButton.Click
        Try
            Dim productModelID As Integer = Integer.Parse(ProductModelIDTextBox.Text, CultureInfo.InvariantCulture)
            TransformAndBrowseDocument(GetSoapRequestXml(productModelID))
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
    Private Sub ShowXSLButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ShowXSLButton.Click
        Try
            Using fs As StreamReader = File.OpenText(instructionsXsltFileName)
                TransformAndBrowseDocument(fs.ReadToEnd())
            End Using
        Catch exception As System.Exception
            webBrowser1.DocumentText = exception.ToString()
        End Try
    End Sub

    Private Overloads Sub TransformAndBrowseDocument(ByVal xmlDocument As String)
        Using sr As New StringReader(xmlDocument)
            Using xtr As New XmlTextReader(sr)
                Dim doc As New XPathDocument(xtr)
                TransformAndBrowseDocument(doc)
            End Using
        End Using
    End Sub

    Private Overloads Sub TransformAndBrowseDocument(ByVal doc As XPathDocument)
        Dim xslt As New XslCompiledTransform()
        Using xsltStreamReader As StreamReader = File.OpenText(prettyXmlXsltFileName)
            Using xsltXmlReader As XmlReader = XmlReader.Create(xsltStreamReader)
                xslt.Load(xsltXmlReader)
            End Using
        End Using

        Dim resultStringWriter As New StringWriter(CultureInfo.InvariantCulture)
        Dim resultXmlWriter As New XmlTextWriter(resultStringWriter)

        Try
            xslt.Transform(doc, New XsltArgumentList(), resultXmlWriter)
            resultXmlWriter.Flush()
        Finally
            resultXmlWriter.Close()
        End Try

        webBrowser1.DocumentText = resultStringWriter.ToString()
    End Sub
End Class